package cn.com.generaldata.os.service.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.entity.Record;
import org.nutz.dao.impl.sql.SqlTemplate;
import org.nutz.dao.sql.Criteria;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import cn.com.generaldata.jsme_indicator_system.entity.UnitRelationNz;
import cn.com.generaldata.os.constant.FilterConstant;
import cn.com.generaldata.os.constant.ReportConstant;
import cn.com.generaldata.os.dao.intf.BaseDAOInterface;
import cn.com.generaldata.os.paging.Event;
import cn.com.generaldata.os.paging.Filter;
import cn.com.generaldata.os.paging.FilterRule;
import cn.com.generaldata.os.paging.Page;
import cn.com.generaldata.os.paging.Result;
import cn.com.generaldata.os.pojo.EnterpriseIndustry;
import cn.com.generaldata.os.pojo.Industry;
import cn.com.generaldata.os.pojo.User;
import cn.com.generaldata.os.pojo.UserIndustry;
import cn.com.generaldata.os.util.MD5Util;
import cn.com.generaldata.os.vo.FuncVO;

@Component
public class UserService {

	private static Logger log = LoggerFactory.getLogger(UserService.class);
	private static final String DEFAULT_PASSWORD = "12345678";

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<User> userDAO;

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<UserIndustry> userIndustryDAO;

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<EnterpriseIndustry> enterpriseIndustryDAO;

	@Autowired
	private Dao indicatorSystemDao;

	@Autowired
	@Qualifier("baseDAO")
	private BaseDAOInterface<Industry> industryDAO;

	@Autowired
	private AuthorityService authorService;
	
	@Autowired
	private SqlTemplate sqlTemplate;
	
	@Autowired
	private Dao daoSys;

	public String createUser(User user) {
		// Boolean ret=true;
		if (user == null || StringUtils.isBlank(user.getUserLoginname())) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("user为空");
			return null;
		}
		// 是否存在有效状态的相同名字的用户(单点登录删除用户后用户为状态无效，可以增加相同名字的用户)
		User existUser = checkLoginname(user.getUserLoginname());
		if (existUser != null) {
			// throw new
			// CommonException(ExceptionConstant.MSG_DUPLICATE_UNIT_NAME);
			log.error("existUser不为空");
			return null;
		}
		// 如果是涉海企业或部门用户
		if (user.getRole().getId().equals("3") || user.getRole().getId().equals("5")) {
			// 查看企业是否存在用户
			existUser = checkUnitname(user.getUserUnit().getId().trim(), null);
			if (existUser != null) {
				// throw new
				// CommonException(ExceptionConstant.MSG_DUPLICATE_UNIT_NAME);
				log.error("existUser不为空");
				return null;
			}
		}

		// 判断密码是否需要制定缺省密码
		if (StringUtils.isBlank(user.getUserPasswd())) {
			user.setUserPasswd(DEFAULT_PASSWORD);
		}

		// MD5密码加密
		user.setUserPasswd(MD5Util.getMD5ofStr(user.getUserPasswd()));
		if (user.getId() == null || "".equals(user.getId()))
			user.setId(UUID.randomUUID().toString().replaceAll("-", ""));
		user.setUserFlag("0");
		userDAO.save(user);

		// webservice调用开始
		//		ModelSend mo = new ModelSend();
		//		mo.setObj(user);
		//		mo.setFlag("4");
		//		new Thread(mo).start();
		// webservice调用结束

		return user.getId();
	}

	public User checkUnitname(String unitId, String id) {
		Filter filter = new Filter();
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "userUnit.id", unitId));
		if (StringUtils.isNotBlank(id)) {
			filter.addRule(new FilterRule(FilterConstant.NOT_EQUAL, "id", id.trim()));
		}

		List<User> users = userDAO.find(User.class, filter, null);
		if (users.size() > 0) {
			return users.get(0);
		}
		return null;
	}

	public User modifyUser(User user) {
		// Boolean ret=true;
		if (user == null) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("user为空");
			return null;
		}
		user.setUserFlag("0");
		userDAO.update(user);

		// webservice调用开始
		//		ModelSend mo = new ModelSend();
		//		mo.setObj(user);
		//		mo.setFlag("3");
		//		new Thread(mo).start();
		// webservice调用结束

		return user;
	}

	public User queryUserById(String id) {
		if (id != null) {
			return userDAO.get(User.class, id);
		}
		return null;
	}

	public User login(String loginName, String password) {
		if (StringUtils.isBlank(loginName) || StringUtils.isBlank(password)) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("loginName为空");
			return null;
		}

		User user = checkLoginname(loginName.trim());

		if (user == null) {
			// throw new
			// CommonException(ExceptionConstant.MSG_INVALID_LOGIN_NAME);
			log.error("user为空");
			return null;
		}

		if (!MD5Util.getMD5ofStr(password.trim()).equals(user.getUserPasswd())) {
			// throw new
			// CommonException(ExceptionConstant.MSG_INVALID_PASSWORD);
			log.error("密码为空");
			return null;
		}

		return user;
	}

	public User loginNew(String loginName) {
		if (StringUtils.isBlank(loginName)) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("loginName为空");
			return null;
		}

		User user = checkLoginname(loginName.trim());

		if (user == null) {
			// throw new
			// CommonException(ExceptionConstant.MSG_INVALID_LOGIN_NAME);
			log.error("user为空");
			return null;
		}

		return user;
	}

	public Result queryUsers(Filter filter, Page page) {
		List<User> users = userDAO.find(User.class, filter, page);
		int count = userDAO.count(User.class, filter);

		if (page == null) {
			return new Result(1, 1, count, users, new ArrayList<Event>());
		}
		return new Result(page.getPageNumber(), page.getPageSize(), count, users, new ArrayList<Event>());
	}

	public Result queryUsersByHql(String hql, HashMap map, Page page) {
		return userDAO.hqlParam(hql, map, page);
		// int count = userDAO.count(User.class, filter);
		//
		// if (page == null) {
		// return new Result(1, 1, count, users, new ArrayList<Event>());
		// }
		// return new Result(page.getPageNumber(), page.getPageSize(), count, users, new ArrayList<Event>());
	}

	public List<UserIndustry> getUserIndustry(Filter filter) {
		List<UserIndustry> userIndustrys = userIndustryDAO.find(UserIndustry.class, filter, null);
		return userIndustrys;
	}

	public Result queryUsersHql(String hql, Page page, HashMap map) {
		// List<User> users = userDAO.find(User.class, filter, page);
		Result hqlParam = userDAO.hqlParam(hql, map, page);

		return hqlParam;
	}

	public void removeUsers(String[] ids) {
		if (ids == null || ids.length < 1) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			return;
		}

		Filter filter = new Filter();
		filter.addRule(new FilterRule(FilterConstant.COLLECTION, "id", ids));

		List<User> users = userDAO.find(User.class, filter, null);
		if (users != null && users.size() > 0) {
			for (User user : users) {
				user.setEnterpriseUserUseSystem(0);
				user.setUserFlag("0");
				userDAO.update(user);
			}
		}
		// userDAO.delete(users);
	}

	public void changePassword(String loginName, String oldPwd, String newPwd) {
		if (StringUtils.isBlank(loginName) || StringUtils.isBlank(oldPwd) || StringUtils.isBlank(newPwd)) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			return;
		}

		User user = checkLoginname(loginName.trim());

		if (user == null) {
			// throw new
			// CommonException(ExceptionConstant.MSG_INVALID_LOGIN_NAME);
			return;
		}

		if (!MD5Util.getMD5ofStr(oldPwd.trim()).equals(user.getUserPasswd())) {
			// throw new
			// CommonException(ExceptionConstant.MSG_INVALID_PASSWORD);
			return;
		}

		user.setUserPasswd(MD5Util.getMD5ofStr(newPwd.trim()));
		userDAO.update(user);
	}

	public void modifyUserIndustry(List<Industry> industrys) {

	}

	public User modifyIndustry(User user, List<Industry> industrys) {
		Set<UserIndustry> userIndustrySet = new HashSet<UserIndustry>();
		boolean isExist = false; // 不存在
		if (user == null) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("user为空");
			return null;
		}

		// 删除原先关联的industrys
		Filter filter = new Filter();
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", user.getId()));

		List<UserIndustry> userIndustrys = userIndustryDAO.find(UserIndustry.class, filter, null);

		for (UserIndustry userIndustry : userIndustrys) {
			userIndustryDAO.delete(userIndustry);
		}
		if (industrys.size() != 0) {
			// 首先查看当前用户的行业分类中是否存在现在的此次行业ID
			for (Industry industry : industrys) {
				// for (UserIndustry userIndustry : userIndustrys) {
				// //当前用户行业分类ID与新的行业分类ID“相同”,说明已经存在，不用在添加行业分类
				// if(userIndustry.getIndustry().getId().equals(industry.getId())){
				// isExist = true; //已经存在
				// break;
				// }
				// }
				// if(!isExist){ //不存在,进行添加
				UserIndustry userIndustry = new UserIndustry(UUID.randomUUID().toString().replaceAll("-", ""), user,
						industry);
				userIndustryDAO.save(userIndustry);
				userIndustrySet.add(userIndustry);
				// }
				// isExist = false;
			}
		}
		// Set<UserIndustry> userIndustrySet = new HashSet<UserIndustry>();
		// for (Industry industry : industrys) {
		// UserIndustry userIndustry = new UserIndustry(null, user, industry);
		// userIndustryDAO.save(userIndustry);
		// userIndustrySet.add(userIndustry);
		// }
		user.setUserIndustrys(userIndustrySet);

		return user;
	}

	public User addEnterpriseIndustry(User user, List<Industry> industrys) {
		Set<EnterpriseIndustry> enterpriseIndustrySet = new HashSet<EnterpriseIndustry>();
		boolean isExist = false; // 不存在
		if (user == null || industrys == null || industrys.size() < 1) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("user为空");
			return null;
		}

		// 删除原先关联的industrys
		Filter filter = new Filter();
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", user.getId()));

		List<EnterpriseIndustry> enterpriseIndustrys = enterpriseIndustryDAO.find(EnterpriseIndustry.class, filter,
				null);
		for (EnterpriseIndustry userIndustry : enterpriseIndustrys) {
			enterpriseIndustryDAO.delete(userIndustry);
		}
		// 首先查看当前用户的行业分类中是否存在现在的此次行业ID
		for (Industry industry : industrys) {
			// for (EnterpriseIndustry enterpriseIndustry : enterpriseIndustrys)
			// {
			// //当前用户行业分类ID与新的行业分类ID“相同”,说明已经存在，不用在添加行业分类
			// if(enterpriseIndustry.getIndustry().getId().equals(industry.getId())){
			// isExist = true; //已经存在
			// break;
			// }
			// }
			System.out.print(user.getId());
			// if(!isExist){ //不存在,进行添加
			User usertemp = new User();
			usertemp.setId(user.getId());
			EnterpriseIndustry enterpriseIndustry = new EnterpriseIndustry(UUID.randomUUID().toString()
					.replaceAll("-", ""), usertemp, industry);
			enterpriseIndustryDAO.save(enterpriseIndustry);
			enterpriseIndustrySet.add(enterpriseIndustry);
			// }
			// isExist = false;
		}

		user.setEnterpriseIndustrys(enterpriseIndustrySet);

		return user;
	}

	public User deleteIndustry(User user, String industryId) {
		if (user == null || industryId == null) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("user为空");
			return null;
		}

		// 删除原先关联的ReportType
		Filter filter = new Filter();
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", user.getId()));
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "industry.id", industryId));

		List<UserIndustry> userIndustrys = userIndustryDAO.find(UserIndustry.class, filter, null);

		for (UserIndustry userIndustry : userIndustrys) {
			userIndustryDAO.delete(userIndustry);
		}

		// UserIndustry userIndustry = new UserIndustry(null, user,
		// industryDAO.get(Industry.class, industryId));
		// userIndustryDAO.delete(userIndustry);

		return user;
	}

	public User deleteEnterpriseIndustry(User user, String industryId) {
		if (user == null || industryId == null) {
			// throw new
			// CommonException(ExceptionConstant.MSG_ILLEGAL_PARAMETER);
			log.error("user为空");
			return null;
		}

		// 删除原先关联的ReportType
		Filter filter = new Filter();
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "user.id", user.getId()));
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "industry.id", industryId));

		List<EnterpriseIndustry> enterpriseIndustrys = enterpriseIndustryDAO.find(EnterpriseIndustry.class, filter,
				null);

		for (EnterpriseIndustry enterpriseIndustry : enterpriseIndustrys) {
			enterpriseIndustryDAO.delete(enterpriseIndustry);
		}

		// UserIndustry userIndustry = new UserIndustry(null, user,
		// industryDAO.get(Industry.class, industryId));
		// userIndustryDAO.delete(userIndustry);

		return user;
	}

	public User checkLoginname(String loginname) {
		Filter filter = new Filter();
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "userLoginname", loginname.trim()));
		filter.addRule(new FilterRule(FilterConstant.EQUAL, "enterpriseUserUseSystem", 1));
		List<User> users = userDAO.find(User.class, filter, null);
		if (users != null && users.size() > 0) {
			return users.get(0);
		}
		return null;
	}

	public cn.com.generaldata.os.vo.ResultVO<cn.com.generaldata.os.vo.UserVO> toVoResult(
			cn.com.generaldata.os.paging.Result pResult) {
		cn.com.generaldata.os.vo.ResultVO<cn.com.generaldata.os.vo.UserVO> result = new cn.com.generaldata.os.vo.ResultVO<cn.com.generaldata.os.vo.UserVO>();

		List<cn.com.generaldata.os.vo.UserVO> users = new ArrayList<cn.com.generaldata.os.vo.UserVO>();
		for (cn.com.generaldata.os.pojo.User pUser : (List<cn.com.generaldata.os.pojo.User>) pResult
				.getOperationResult()) {
			users.add(toVo(pUser));
		}
		result.setOperationResult(users);
		result.setPageNumber(pResult.getPageNumber());
		result.setPageSize(pResult.getPageSize());
		result.setTotalCount(pResult.getTotalCount());

		return result;
	}

	public cn.com.generaldata.os.vo.UserVO toVo(User pUser) {
		if (pUser != null) {
			String roleId = pUser.getRole() == null ? null : pUser.getRole().getId();
			String roleName = pUser.getRole() == null ? null : pUser.getRole().getRoleName();
			String industryId = pUser.getUserIndustryId() == null ? null : pUser.getUserIndustryId();
			String industryName = null;
			String areaId = null;
			String areaName = null;
			if (pUser.getUserUnit() != null && pUser.getUserUnit().getArea() != null) {
				areaId = pUser.getUserUnit().getArea().getId();
				areaName = pUser.getUserUnit().getArea().getAreaDesc();
			}
			String unitId = pUser.getUserUnit() == null ? null : pUser.getUserUnit().getId();
			String unitName = pUser.getUserUnit() == null ? null : pUser.getUserUnit().getUnitName();

			if (ReportConstant.YONGHAI_UNIT.equals(roleId)) {
				if (pUser.getUserUnit().getUnitProper() != null) {
					if (pUser.getUserUnit().getUnitProper().indexOf("1") != -1) {
						roleName = "涉海企业用户";
					}
					if (pUser.getUserUnit().getUnitProper().indexOf("2") != -1) {
						roleName = "用海企业用户";
					}
					if (pUser.getUserUnit().getUnitProper().indexOf("3") != -1) {
						roleName = "开发区企业用户";
					}
				}
			}

			List<String> userIndustrys = new ArrayList<String>();
			if (pUser.getUserIndustrys() != null) {
				for (UserIndustry userIndustry : pUser.getUserIndustrys()) {
					userIndustrys.add(userIndustry.getIndustry().getId());
				}
			}

			List<String> enterpriseIndustrys = new ArrayList<String>();
			if (pUser.getEnterpriseIndustrys() != null) {
				for (EnterpriseIndustry enterpriseIndustry : pUser.getEnterpriseIndustrys()) {
					enterpriseIndustrys.add(enterpriseIndustry.getIndustry().getId());
				}
			}
			String authorId = pUser.getAuthorId();
			List<String> funcs = new ArrayList<String>();
			List<FuncVO> funcsByAuthor = authorService.getFuncsByAuthor(authorId);
			if (funcsByAuthor != null) {
				for (FuncVO func : funcsByAuthor) {
					funcs.add(func.getId());
				}
			}
			return new cn.com.generaldata.os.vo.UserVO(pUser.getId(), roleId, roleName, industryId, industryName,
					areaId, areaName, pUser.getUserLoginname(), null, pUser.getUserRegionName(),
					pUser.getUserRegionOcean(), pUser.getUserCityName(), pUser.getUserDepartmentName(),
					pUser.getUserRegionCode(), unitName, unitId, pUser.getUserInstitutionName(),
					pUser.getUserInstitutionCode(), pUser.getUserDomainName(), pUser.getUserDomainCode(),
					pUser.getUserUnitAdmin(), pUser.getUserStatAdmin(), pUser.getUserFillAdmin(),
					pUser.getUserContactPerson(), pUser.getUserContactPhone(), pUser.getUserFlag(), pUser.getDl(),
					pUser.getZl(), pUser.getXl(), pUser.getLm(), pUser.getHyl(), pUser.getAddr(), pUser.getQh(),
					pUser.getYwhd(), pUser.getMc(), pUser.getDwfl(), pUser.getHy2002(), pUser.getHy2011(),
					pUser.getZclx(), pUser.getKgqk(), pUser.getJglx(), pUser.getYyzt(), pUser.getLsgx(),
					pUser.getBbdw(), pUser.getUserStatAdminTel(), pUser.getUserStat(), pUser.getUserStatTel(),
					pUser.getUserFaxTel(), pUser.getUserEmial(), pUser.getCompanyUrl(), pUser.getProduct1(),
					pUser.getProduct2(), pUser.getProduct3(), pUser.getOceanIndustryName(),
					pUser.getOceanIndustryCode(), pUser.getMostlyTaking(), pUser.getSuperCompany(),
					pUser.getSuperCompanyCode(), pUser.getRegistAdd(), pUser.getCompanySynopsis(),
					pUser.getUserReportedDataType(), pUser.getCorporationAndTel(), pUser.getPractitioner(),
					pUser.getAssetTotal(), pUser.getTaking(), pUser.getEnterpriseUserUseSystem(), userIndustrys,
					enterpriseIndustrys, pUser.getAuthorId(), funcs);
		}
		return null;
	}

	/**
	 * 查询父级单位用户
	 */
	public List<User> findParentUser(String uid) {
		Criteria cri = Cnd.cri();
		cri.where().and("cid", "=", uid);
		cri.where().and("depth", "=", 1);
		List<UnitRelationNz> urList = indicatorSystemDao.query(UnitRelationNz.class, cri);
		List<User> list = new ArrayList<User>();
		for (UnitRelationNz ur : urList) {
			String pid = ur.getPid();
			Filter filter = new Filter();
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "userUnit.id", pid));// 现省局级角色id为4
			List<User> find = userDAO.find(User.class, filter, null);
			list.addAll(find);
		}
		return list;
	}
	
	public String getModuleName(String authorId){
		String sql = "select func from TBL_FUNC t where t.id in (select a.func_id from TBL_AUTHOR_FUNC a where a.author_id = '" + authorId + "')";
		List<String> record = sqlTemplate.queryForList(sql, null, null, String.class);

		StringBuilder sb= new StringBuilder();
		
		for (String str :  record){
			sb.append(str).append(",");
		}
		
		return sb.toString();
	}
	
	/**
	 * 获取用户权限信息
	 * @param username
	 * */
	public String getSystemRolename(String username){
		Criteria cri = Cnd.cri();
		cri.where().and("username", "=", username);
		Record re = daoSys.fetch("users", cri);
		return re.getString("rolename");
	}
	
	public String getMd5DefaultPassword(){
		return MD5Util.getMD5ofStr(this.DEFAULT_PASSWORD);
	}
}
